package com.party.notify.wechatNotify.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.party.api.service.wechat.IWechatService;
import com.party.common.constant.Constant;
import com.party.common.redis.StringJedis;
import com.party.common.utils.DateUtils;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.member.ThirdPartyUser;
import com.party.core.model.member.ThirdPartyUserType;
import com.party.core.model.wechat.WechatTemplateMassage;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.service.member.IThirdPartyUserService;
import com.party.core.service.wechat.IWechatTemplateMassageService;
import com.party.core.service.wechatPlatform.IWechatMerchantService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import com.party.notify.template.service.ITemplateService;
import com.party.notify.wechatNotify.service.IWechatKeynotService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 微信消息内容接口实现
 * Created by wei.li
 *
 * @date 2017/5/17 0017
 * @time 18:19
 */

@Service
public class WechatKeynotService implements IWechatKeynotService {



    @Autowired
    private IThirdPartyUserService thirdPartyUserService;

    @Autowired
    private IWechatTemplateMassageService wechatTemplateMassageService;

    @Autowired
    private ITemplateService templateService;

    @Autowired
    private IWechatMerchantService wechatMerchantService;

    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;

    @Autowired
    private StringJedis stringJedis;

    @Autowired
    private IWechatService wechatService;

    private static final String REDIS_XCX_FORMID_LIST_KEY = "xcxFormIdListKey";

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 获取微信消息内容值
     * @param value 值
     * @return 消息内容
     */
    public JSONObject get(String value) {
        JSONObject object = new JSONObject();
        object.put("value", value);
        object.put("color", Constant.WECHAT_MESSAGE_COLOR);
        return object;
    }

    /**
     * 封装标题和尾部
     * @param wechatTemplateMassage 模板消息
     * @return 消息内容
     */
    @Override
    public JSONObject appendFirstAndLast(WechatTemplateMassage wechatTemplateMassage, JSONObject jsonObject) {
        if (null == jsonObject.get("first") && !Strings.isNullOrEmpty(wechatTemplateMassage.getFirst())) {
            JSONObject jsonFirst = this.get(wechatTemplateMassage.getFirst());
            jsonObject.put("first", jsonFirst);
        }

        if (null == jsonObject.get("remark") && !Strings.isNullOrEmpty(wechatTemplateMassage.getRemark())) {
            JSONObject jsonRemark = this.get(wechatTemplateMassage.getRemark());
            jsonObject.put("remark", jsonRemark);
        }
        return jsonObject;
    }


    /**
     * 封装微信模板消息配置
     * @param memberId
     * @param accessToken1 消息事件编码
     * @param appId1 消息事件编码
     * @param notifyCode 消息事件编码
     * @param authorId 接受者
     * @param constant 消息内容
     * @param jsonData 微信消息内容
     * @return 消息内容
     */
    public HashMap<String, Object> getWechatConstant(String memberId, String accessToken1, String appId1, String notifyCode,
                                                     String authorId, HashMap<String, Object> constant,
                                                     JSONObject jsonData, HashMap<String, Object> urlConstant){

        List<ThirdPartyUser> thirdPartyUserList;
        WechatTemplateMassage wechatTemplateMassage = null;
        WechatOpenMember wechatOpenMember = wechatOpenMemberService.findByMemberId(memberId);
        String accessToken = null;
        String appId = null;
        if (null != wechatOpenMember) {
            accessToken = wechatOpenMember.getAuthorizerAccessToken();
            appId = wechatOpenMember.getAuthorizerAppid();
        }


        if (StringUtils.isNotEmpty(accessToken) && StringUtils.isNotEmpty(appId)) {
            logger.error("微信推送消息--notifyCode：{}，accessToken：{}，appId：{}", notifyCode, accessToken, appId);
            //发送者
            thirdPartyUserList = thirdPartyUserService.get(3, authorId, appId);

            // 修改为根据appid查询
            wechatTemplateMassage = wechatTemplateMassageService.getPartner(appId, notifyCode);
        }
        // 走系统配置
        else {
            wechatOpenMember = wechatOpenMemberService.getSystem();
            accessToken = wechatOpenMember.getAuthorizerAccessToken();
            appId = wechatOpenMember.getAuthorizerAppid();
            thirdPartyUserList = thirdPartyUserService.get(3, authorId, appId);
            wechatTemplateMassage = wechatTemplateMassageService.getSystem(notifyCode);
        }

        //微信账户
        List<String> openIdList = LangUtils.transform(thirdPartyUserList, new Function<ThirdPartyUser, String>() {
            public String apply(ThirdPartyUser thirdPartyUser) {
                return thirdPartyUser.getThirdPartyId();
            }
        });

        if (null == wechatTemplateMassage) {
            logger.error("消息模板配置不存在，appid:{},notifyCode:{}", appId, notifyCode);
        }

        //如果存在消息模板
        if (null != wechatTemplateMassage){
            jsonData = this.appendFirstAndLast(wechatTemplateMassage, jsonData);
            constant.put(Constant.WECHAT_NOTIFY_KEY, jsonData);
            String url = templateService.replaceUrl(wechatTemplateMassage.getUrl(), urlConstant);
            //替换url
            constant.put("templateUrl", url);
            constant.put("templateId", wechatTemplateMassage.getTemplateId());
        }

        constant.put("openIdList", openIdList);
        constant.put("accessToken", accessToken);
        return constant;
    }


    /**
     * 封装微信模板消息配置
     * @param targetMemberId 目标商户
     * @param notifyCode 消息事件编码
     * @param authorId 接受者
     * @param constant 消息内容
     * @param jsonData 微信消息内容
     * @return
     */
    public HashMap<String, Object> getWechatConstant(String targetMemberId, String notifyCode,
                                                     String authorId, HashMap<String, Object> constant,
                                                     JSONObject jsonData, HashMap<String, Object> urlConstant){
        return this.getWechatConstant(targetMemberId, null, null, notifyCode, authorId, constant, jsonData, urlConstant);
    }


    /**
     * 封装微信模板消息配置
     * @param notifyCode 消息事件编码
     * @param authorId 接受者
     * @param constant 消息内容
     * @param jsonData 微信消息内容
     * @return
     */
    public HashMap<String, Object> getWechatConstant( String notifyCode, String authorId,
                                                      HashMap<String, Object> constant, JSONObject jsonData, HashMap<String, Object> urlConstant){
        return this.getWechatConstant(null, null, null, notifyCode, authorId, constant, jsonData, urlConstant);
    }

    @Override
    public HashMap<String, Object> getWechatXcxConstant(String wechatAccountType, String notifyCode,
                                                        String authorId, HashMap<String, Object> constant,
                                                        JSONObject jsonData, HashMap<String, Object> urlConstant) throws Exception {
        WechatOpenMember openMember = wechatOpenMemberService.findByType(wechatAccountType);
        if (openMember == null) {
            throw new Exception("没有对应小程序的配置");
        }
        String accessToken = openMember.getAuthorizerAccessToken();
        if (StringUtils.isEmpty(accessToken)) {
            throw new Exception("accessToken不能为空");
        }
        List<ThirdPartyUser> thirdPartyUserList = thirdPartyUserService.
                get(ThirdPartyUserType.WECHAT_MINI_PROGRAM.getCode(), authorId, openMember.getAuthorizerAppid());

        WechatTemplateMassage wechatTemplateMassage = wechatTemplateMassageService.getByType(Constant.WECHAT_TEMPLATE_TYPE, notifyCode);
        if (wechatTemplateMassage == null) {
            throw new Exception("没有找到对应消息模板");
        }
        //微信账户
        List<String> openIdList = LangUtils.transform(thirdPartyUserList, new Function<ThirdPartyUser, String>() {
            public String apply(ThirdPartyUser thirdPartyUser) {
                return thirdPartyUser.getThirdPartyId();
            }
        });
        if (openIdList.size() == 0) {
            throw new Exception("没有找到对应用户的openID");
        }

        // 获取formID
        String formId = null;
        String formIdToDay = null;
        String memberId = (String) constant.get("memberId");
        String jedisValue = stringJedis.getValue(REDIS_XCX_FORMID_LIST_KEY);
        if (StringUtils.isNotEmpty(jedisValue)) {
            JSONObject jsonObject = JSONObject.parseObject(jedisValue);
            Object memberJsonObject = jsonObject.get(memberId);
            if (memberJsonObject == null) {
                throw new Exception(memberId + "用户没有对应的formId");
            }
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -6);
            List<Date> dateList = DateUtils.getDateDifference(calendar.getTime(), new Date());
            for (Date date : dateList) {
                String formDate = DateUtils.formatDate(date, DateUtils.DATE_PATTERN);
                Object formIdData = ((JSONObject) memberJsonObject).get(formDate);
                if (formIdData == null || ((JSONArray) formIdData).size() == 0) {
                    if (date.before(new Date())) {
                        ((JSONObject) memberJsonObject).remove(formDate);
                    }
                    continue;
                } else {
                    if (((JSONArray) formIdData).size() > 0) {
                        formId = ((JSONArray) formIdData).get(0).toString();
                        formIdToDay = formDate;
                        ((JSONArray) formIdData).remove(0);
                    }
                    break;
                }
            }
            stringJedis.setValue(REDIS_XCX_FORMID_LIST_KEY, JSONObject.toJSONString(jsonObject));
        }
        if (StringUtils.isEmpty(formId)) {
            throw new Exception("没有找到对应用户的formId");
        }
        constant.put(Constant.WECHAT_NOTIFY_KEY, jsonData);
        String url = templateService.replace(wechatTemplateMassage.getUrl(), urlConstant);
        constant.put("templateUrl", url);
        constant.put("templateId", wechatTemplateMassage.getTemplateId());
        constant.put("formId", formId);
        constant.put("openIdList", openIdList);
        constant.put("accessToken", accessToken);
        constant.put("memberId", memberId);
        constant.put("formIdToDay", formIdToDay);

        logger.info("发送小程序模板消息内容：{}", JSONObject.toJSONString(constant));
        return constant;
    }
}
